package com.autumn.config.environment;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;

import com.autumn.config.api.CloudConfigService;
import com.autumn.config.api.vo.ServiceProfileInfo;
import com.autumn.config.api.vo.ServiceProfileValue;

/**
 * Autumn 环境仓储
 * 
 * @author 老码农
 *         <p>
 *         Description
 *         </p>
 * @date 2018-01-21 22:16:59
 */
public class DatabaseEnvironmentRepository implements EnvironmentRepository {

	@Autowired
	private CloudConfigService configService;	

	@Override
	public Environment findOne(String application, String profile, String label) {
		String name = null;
		String version = "";
		Map<String, Object> profileMap = null;

		ServiceProfileValue input = new ServiceProfileValue();
		input.setServiceId(application);
		input.setProfile(profile);
		input.setLabel(label);
		ServiceProfileInfo serviceProfile = configService.serviceProfile(input);
		if (serviceProfile != null) {
			label = serviceProfile.getLabel();
			version = serviceProfile.getVersion().toString();
			name = serviceProfile.getProfileName();
			profileMap = serviceProfile.getProfileMap();
		} else {
			profileMap = new LinkedHashMap<>();
			label = "master";
			name = String.format("%s-%s.%s", application, profile, "yml");
		}		
		Environment env = new Environment(application, new String[] { profile }, label, version, "");
		env.add(new PropertySource(name, profileMap));
		return env;
	}
}
